<?php

namespace App\Providers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot(): void
    {
        if ((bool)env('SQL_LOG', false) == false) {
            return;
        }
        DB::listen(
            function ($sql) {
                foreach ($sql->bindings as $i => $binding) {
                    if ($binding instanceof \DateTime) {
                        $sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
                    } else {
                        if (is_string($binding)) {
                            $sql->bindings[$i] = "'$binding'";
                        }
                    }
                }
                // 使用 preg_replace_callback 代替简单替换，只处理占位符 ?
                $query = preg_replace_callback('/\?/', function ($matches) use (&$sql) {
                    static $index = 0;
                    return isset($sql->bindings[$index]) ? $sql->bindings[$index++] : '?';
                }, $sql->sql);

                // 添加错误抑制符防止格式化错误中断程序
                $logContent = @vsprintf(str_replace('%', '%%', $sql->sql), $sql->bindings);

                $logFile = fopen(
                    storage_path('logs' . DIRECTORY_SEPARATOR . 'sql-' . date('Y-m-d') . '.log'),
                    'a+'
                );
                fwrite($logFile, '[' . date('Y-m-d H:i:s') . '] ' . $logContent . ';' . PHP_EOL);
                fclose($logFile);
            }
        );
    }
}
